package com.efounder.message.socket;

import android.util.Log;

import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct001;
import com.efounder.message.struct.IMStruct002;
import com.efounder.message.struct.IMStruct003;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


public class JFSocketHandler extends SimpleChannelInboundHandler<String> {
    private static final String TAG = "JFSocketHandler";
    private OnChannelActiveListener onChannelActiveListener;

    public JFSocketHandler() {
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg)
            throws Exception {
        Log.d(TAG, "channelRead0->msg=" + msg);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
//		super.channelRead(ctx, msg);

        ByteBuf buffer = Unpooled.buffer();
        buffer.writeBytes((byte[]) msg);
        byte messageType = buffer.readByte();
        switch ((int) messageType) {
            //2表示接收到别人给我发送的消息
            case 2: {
                IMStruct002 struct = new IMStruct002();
                struct.setMsgLength(buffer.readInt());

                //9.10新加
                struct.setVersion(buffer.readShort());

                struct.setFromUserId(buffer.readInt());
                struct.setToUserId(buffer.readInt());
                struct.setTime(buffer.readLong());
                struct.setServerTime(buffer.readLong());
                struct.setMsgId(buffer.readInt());
                struct.setToUserType(buffer.readByte());
                struct.setMessageChildType(buffer.readShort());
                int contentLength = buffer.readInt();
                byte[] body = new byte[contentLength];
                buffer.readBytes(body);
                struct.setBody(body);

                //9.10新加
                struct.setIsHavePMsgId(buffer.readByte());
                if (struct.getIsHavePMsgId() == 1) {
                    byte[] vbpMsgId = new byte[42];
                    buffer.readBytes(vbpMsgId);
                    struct.setpMsgId(new String(vbpMsgId));
                }
                struct.setpUserId(buffer.readInt());

                if (buffer.isReadable(10)) {
//					byte[] ext = new byte[10];
//					buffer.readBytes(ext);
//					struct.setOffline(ext[0]);
                    struct.setOffline(buffer.readByte());
                    struct.setIntegralType(buffer.readByte());
                    struct.setIntegralSubtype(buffer.readByte());
                    struct.setIntegral(buffer.readShort());
                }

                //收到消息处理事件
                JFMessageManager.getInstance().messageReceive(struct);
                //Log.i(TAG,"channelRead------>" + struct.toString());
                break;
            }
            //3表示我给服务器发送的消息，服务器收到后给我的回执
            case 3: {
                IMStruct003 struct = new IMStruct003();
                struct.setMsgLength(buffer.readInt());

                byte[] msgIdByte = new byte[42];
                buffer.readBytes(msgIdByte);

                struct.setMsgId(new String(msgIdByte));
                struct.setAckType(buffer.readByte());
                struct.setTime(buffer.readLong());
                Log.d(TAG, "回执消息messageID：" + struct.getMsgId());
                JFMessageManager.getInstance().receiptReceive(struct);

            }
        }
        buffer.release();
        Log.d(TAG, "channelRead->msg=" + msg.toString() + "msgType: " + messageType);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);

        Log.d(TAG, "channelRegistered");

    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);

        if (onChannelActiveListener != null) {
            onChannelActiveListener.onChannelActiveFail();
        }

        Log.d(TAG, "channelUnregistered");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);

        Log.d(TAG, "channelReadComplete");

    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx)
            throws Exception {
        super.channelWritabilityChanged(ctx);

        Log.d(TAG, "channelWritabilityChanged");

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);

        Log.i(TAG, "-------激活通道成功（连接消息服务成功）Client active");
//		JFMessageManager.isChannelActive = true;
        JFMessageManager.getInstance();
        //XXX 向服务器发送一条注册消息
        IMStruct001 im = new IMStruct001();
        im.setClientId(JFSocketManager.token);
        IMStruct002 latMessage = JFMessageManager.dbManager.getLastReceiveMessage();
        if (latMessage != null) {
            im.setLastMessageTime(String.valueOf(latMessage.getServerTime()));
        }
        JFMessageManager.getInstance().sendStruct(im);
        if (onChannelActiveListener != null) {
            onChannelActiveListener.onChannelActiveSuccess();
        }
        //启动心跳
        JFSocketManager.getInstance().startTimer();

//		//XXX　网络连接，发送未发送的消息
//		for (int i = 0; i < JFMessageManager.unsendMessageQueue.size(); i++) {
//			Log.i("--", "发送未发送的消息-----" + i);
//			IMStruct struct = JFMessageManager.unsendMessageQueue.get(i);
//			JFSocketManager.sendMessage(struct.toByteArray());
//		}
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

//		JFMessageManager.isChannelActive = false;
        Log.i(TAG, "Client close");
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
//		JFMessageManager.isChannelActive = false;
        cause.printStackTrace();
    }

    public void setOnChannelActiveListener(
            OnChannelActiveListener onChannelActiveListener) {
        this.onChannelActiveListener = onChannelActiveListener;
    }


    public interface OnChannelActiveListener {

        void onChannelActiveSuccess();

        void onChannelActiveFail();

    }
}
